package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.mysql.cj.util.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.hmdp.constant.MessageConstant.*;
import static com.hmdp.constant.RedisConstants.*;
import static com.hmdp.constant.SystemConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 2025/07/15
     * 发送手机验证码
     */
    @Override
    public Result sendCode(String phone){
        //验证手机号的格式,如果正确继续往下执行，如果错误则退出
        boolean phoneInvalid = RegexUtils.isPhoneInvalid(phone);
        if(phoneInvalid){
            return Result.fail(PHONR_FORMAT_FAIL);
        }
        //正确，发送验证码
        String code = RandomUtil.randomNumbers(6);
        log.info("验证码发送成功：{}",code);
        //保存验证码到redis
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY+ phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //返回
        return Result.ok();
    }

    /**
     * 2025/07/15
     * 登录功能
     */
    @Override
    public Result login(LoginFormDTO loginForm){
        //校验手机号格式
        if(RegexUtils.isPhoneInvalid(loginForm.getPhone())){//true为无效，反之
            return Result.fail(PHONR_FORMAT_FAIL);
        }
        //校验验证码
        String code = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY+ loginForm.getPhone());
        if(code == null || !Objects.equals(code,loginForm.getCode())){
            return Result.fail(CODE_NOT_EQUALS);
        }
        //判断是否是新用户，若是则添加进数据库，若不是则查询信息
        User user = query().eq(PHONE, loginForm.getPhone()).one();
        if(user == null){//新用户
            String nickName  = RandomUtil.randomString(6);
            user = User.builder()
                            .nickName(USER_NICK_NAME_PREFIX + nickName)
                            .phone(loginForm.getPhone())
                            .createTime(LocalDateTime.now())
                            .updateTime(LocalDateTime.now())
                            .build();
            save(user);
        }
        //用户信息保存到redis
        String token = UUID.randomUUID().toString();
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user, userDTO);
        Map<String, Object> map = BeanUtil.beanToMap(userDTO,new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldName,fieldValue)->fieldValue.toString()));
//        Map<String,Object> map = new HashMap<>();
//        map.put("id",userDTO.getId().toString());
//        map.put("nickName",userDTO.getNickName());
//        map.put("icon",userDTO.getIcon());
        String stringToken  = LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(stringToken,map);
        //设置token有效期
        stringRedisTemplate.expire(stringToken,LOGIN_USER_TTL, TimeUnit.MINUTES);
        //返回token
        return Result.ok(token);
    }

}
